﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using TjZheng.Domain.DataEntity;

namespace TjZheng.Editor
{
    /// <summary>
    /// Crawler 的摘要说明
    /// </summary>
    public class CrawlerHandler : Handler
    {
        private string[] Sources;
        private Crawler[] Crawlers;
        /// <summary>
        /// 上传资源限制
        /// </summary>
        public UploadLimit UploadLimit { get; set; }
        public CrawlerHandler(HttpContext context) : base(context) { }
        public CrawlerHandler(HttpContext context, UploadLimit objUploadLimit)
            : base(context)
        {
            this.UploadLimit = objUploadLimit;
        }

        public override void Process()
        {
            Sources = Request.Form.GetValues("source[]");
            if (Sources == null || Sources.Length == 0)
            {
                WriteJson(new
                {
                    state = "参数错误：没有指定抓取源"
                });
                return;
            }
            Crawlers = Sources.Select(x => new Crawler(x, Server).Fetch(this.UploadLimit)).ToArray();
            WriteJson(new
            {
                state = "SUCCESS",
                list = Crawlers.Select(x => new
                {
                    state = x.State,
                    source = x.SourceUrl,
                    url = x.ReturnPath
                })
            });
        }
    }
}